/*
 * sabnzb.c
 *
 *  Created on: Feb 5, 2012
 *      Author: daniel
 */

#include "sabnzb.h"
#include "pollerutils.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "../renderers/download.h"

#include "../cJSON.h"
#include <curl/curl.h>
#include <glib.h>

//		 "timeleft":     "0:00:15",
//		 "mb":   397.429047,
//  	 "msgid":        "",
//		 "filename":     "qi",
//		 "mbleft":       58.220079,
//		 "id":   "SABnzbd_nzo_UcPu7P"

#define JOB_FILENAME "filename"
#define JOB_MBLEFT "mbleft"
#define JOB_ID "id"

static GHashTable* downloads;

static void markdownloads(gpointer key, gpointer value, gpointer user_data) {
	job_t* j = value;
	j->mark = true;
}

static gboolean cleandownloads(gpointer key, gpointer value, gpointer user_data) {
	job_t* j = value;

	if (j->mark) {
		download_del(j);
	}

	return j->mark;
}

static void poll() {

	g_hash_table_foreach(downloads, markdownloads, NULL);

	expandinglump_t chunk;
	pollerutils_httpget(
			"http://192.168.2.253:8081/api?mode=qstatus&output=json&apikey=7ef474c6d5ea9ac5f0adaf960ea1f3dd",
			&chunk);

	cJSON* root = cJSON_Parse(chunk.memory);
	if (root != NULL) {
		cJSON* jobs = cJSON_GetObjectItem(root, "jobs");

		if (jobs != NULL) {
			cJSON* job = jobs->child;
			while (job != NULL) {

				char* id = cJSON_GetObjectItem(job, JOB_ID)->valuestring;
				double mbleft =
						cJSON_GetObjectItem(job, JOB_MBLEFT)->valuedouble;

				job_t* j = g_hash_table_lookup(downloads, id);
				if (j == NULL) {
					char* filename =
							cJSON_GetObjectItem(job, JOB_FILENAME)->valuestring;
					if (filename == NULL) {
						printf("filename is null\n");
						break;
					}
					j = download_job_create(id, filename);
					g_hash_table_insert(downloads, j->id, j);
					download_add(j);
				}

				j->mbleft = mbleft;
				j->mark = false;

				job = job->next;
			}
		}

		cJSON_Delete(root);
	}

	free(chunk.memory);

	g_hash_table_foreach_remove(downloads, cleandownloads, NULL);

}

static void create() {
	downloads = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
			download_job_destroyvalue);
}

static void dispose() {
	g_hash_table_remove_all(downloads);
	g_hash_table_destroy(downloads);
}

static void parseconfig(cJSON* lump) {
}

poller_t sabnzbpoller = { "sabnzb", create, parseconfig, poll, dispose };
